package com.weilele.library.websocket

import com.weilele.mvvm.mainHandler
import com.weilele.mvvm.utils.`object`.NetWorkObj
import com.weilele.mvvm.utils.logI

internal abstract class BaseWebSocket : IWebSocket {
    /**
     * 检查重连任务的时间间隔
     */
    private var checkConnectTaskDuration = 10_000L

    /**
     * 是否检查连接任务
     */
    private var enableAutoTask = false

    /**
     * 消息监听器
     */
    protected var onMessageCall: Function1<Any?, Unit>? = null

    /**
     * 状态监听器
     */
    private var onSocketStatusChangeCall: Function1<WebSocketState, Unit>? = null

    /**
     * 自动连接任务
     */
    private var taskRunListener: Function1<IWebSocket, Unit>? = null
    private val autoConnectRun = object : Runnable {
        override fun run() {
            logI { "BaseWebSocket 检查连接状态：$webSocketState" }
            if (isCanAutoConnect()) {
                logI { "BaseWebSocket 可以自动重连：$webSocketState" }
                connect()
            }
            if (enableAutoTask) {
                mainHandler.postDelayed(this, checkConnectTaskDuration)
            }
            taskRunListener?.invoke(this@BaseWebSocket)
        }
    }

    /**
     * 连接状态
     */
    open var webSocketState = WebSocketState.NoConnect
        set(value) {
            field = value
            logI { "BaseWebSocket 连接状态发生变化：$value" }
            onSocketStatusChangeCall?.invoke(value)
        }

    override fun enableAutoConnectTask(
        enable: Boolean,
        duration: Long?,
        taskRunListener: Function1<IWebSocket, Unit>?
    ) {
        enableAutoTask = enable
        this.taskRunListener = taskRunListener
        if (duration != null && duration >= 0) {
            checkConnectTaskDuration = duration
        }
        logI { "BaseWebSocket enableAutoConnectTask：$enableAutoTask" }
        mainHandler.removeCallbacks(autoConnectRun)
        if (enable) {
            mainHandler.post(autoConnectRun)
        }
    }


    override fun disConnect() {
        //手动断开的是否取消自动连接任务，防止资源消耗
        enableAutoConnectTask(false)
    }


    override fun setOnReceiveMessageListener(onMessage: (Any?) -> Unit) {
        onMessageCall = onMessage
    }

    override fun setOnConnectListener(onSocketStatusChange: (WebSocketState) -> Unit) {
        onSocketStatusChangeCall = onSocketStatusChange
    }

    /**
     * 是否可以自动连接
     */
    private fun isCanAutoConnect(): Boolean {
        return enableAutoTask && NetWorkObj.isNetWorkConnect && webSocketState == WebSocketState.NoConnect
    }

    override fun isConnect(): Boolean {
        return webSocketState == WebSocketState.Connected
    }
}